# -*- coding: utf-8 -*-

'''
Created on 27.07.2011

@author: Vlasov A. I. <root@proscript.ru>
'''
import re

from itertools import chain

from django.utils.html import conditional_escape
from django.utils.encoding import force_unicode
from django.utils.safestring import mark_safe

from django.forms.widgets import CheckboxSelectMultiple, Input, CheckboxInput, DateInput

__all__ = (
    'CheckboxSelectMultipleGroups', 'DateInputHTML5', 'PasportInputHTML5', 'PhoneInputHTML5',
)

class CheckboxSelectMultipleGroups(CheckboxSelectMultiple):
    def render(self, name, value, attrs=None, choices=()):
        if value is None: value = []
        has_id = attrs and 'id' in attrs
        
        final_attrs = self.build_attrs(attrs, name=name)
        output = [u'<ul>']
        # Normalize to strings
        str_values = set([force_unicode(v) for v in value])
        grp = None
        for i, (option_value, option_label) in enumerate(chain(self.choices, choices)):
            if not grp and grp != '-':
                if '.' in option_label and re.match(ur'^\d+.\d', option_label, re.U):
                    grp = option_label.split('.')[0]
                else:
                    grp = '-'
                
            # If an ID attribute was given, add a numeric index as a suffix,
            # so that the checkboxes don't all have the same ID attribute.
            if has_id:
                final_attrs = dict(final_attrs, id='%s_%s' % (attrs['id'], i))
                label_for = u' for="%s"' % final_attrs['id']
            else:
                label_for = ''

            cb = CheckboxInput(final_attrs, check_test=lambda value: value in str_values)
            option_value = force_unicode(option_value)
            rendered_cb = cb.render(name, option_value)
            option_label = conditional_escape(force_unicode(option_label))
            
            if grp != '-' and grp != option_label[0:len(grp)]:
                output.append(u'<li class="line">%s</li>'%('-'*20))
                grp = option_label[0:len(grp)]
            
            output.append(u'<li><label%s>%s %s</label></li>' % (label_for, rendered_cb, option_label))
            
        output.append(u'</ul>')
        return mark_safe(u'\n'.join(output))

class DateInputHTML5(DateInput):
    input_type = 'date'
    
class PasportInputHTML5(Input):
    input_type = 'text'
    
    def __init__(self, attrs=None):
        super(PasportInputHTML5, self).__init__(attrs)
        
        self.attrs.update({
            'pattern': u'\d{2}[ ]?\d{2}([ №]{1,2})?\d{6}',
            'placeholder': u'00 00 000000',
            'title': u'Введите номер паспорта по одному из шаблонов: 00 00 000000, 00 00 №000000, 0000 №000000, 0000000000',
        })

class PhoneInputHTML5(Input):
    input_type = 'tel'
    
    def __init__(self, attrs=None):
        super(PhoneInputHTML5, self).__init__(attrs)
        
        self.attrs.update({
            'pattern': u'(([ ]*[\+]?\d[ ]*[\(][ ]*(\d{5}[ ]*[\)][ ]*\d|\d{4}[ ]*[\)][ ]*\d{2}|\d{3}[ ]*[\)][ ]*\d{3})[- ]?\d{2}[- ]?\d{2}|[+]?\d{11}|\d{5})[ ]*([,][ ]*([\+]\d[ ]*[\(][ ]*(\d{5}[ ]*[\)][ ]*\d|\d{4}[ ]*[\)][ ]*\d{2}|\d{3}[ ]*[\)][ ]*\d{3})[- ]?\d{2}[- ]?\d{2}|[+]?\d{11}|\d{5})[ ]*)*|)',
            'placeholder': u'+7(85144) 2-22-22',
            'title': u'Введите номера телефонов по одному из шаблонов через запятую: +7(909) 222-22-22, +7(8512) 22-22-22, +7(85144) 2-22-22, 8514422222, 22222 (для Икрянинского района)',
        })
        